﻿using PSDLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace PSDBurnService
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string username = DeviceUUID.GetUUID();

                int arg_password_index = Array.IndexOf(args, "-p") + 1;
                string password = (args.Length > arg_password_index ? args[arg_password_index] : "");

                int arg_logtype_index = Array.IndexOf(args, "-l") + 1;
                string logtype = (args.Length > arg_logtype_index ? args[arg_logtype_index] : "");

                bool runAsService = !string.IsNullOrEmpty(args.Where(t => t == "--service").FirstOrDefault());

                if (runAsService)
                {
                    RunAsService(username, password, logtype);
                }
                else
                {
                    Run(username, password, logtype);
                }
            }
            else
            {
                ServiceBase[] ServiceToRun = new ServiceBase[] { new PSDBurnWinService() };

                ServiceBase.Run(ServiceToRun);
            }
        }

        private static void Run(string username, string password, string logtype)
        {
            BurnServiceContext context = new BurnServiceContext();

            var result = context.Init(username, password, logtype, false);

            if (result.success)
            {
                context.OpenBurnClient();

                string cmd = "";
                while (cmd != "exit")
                {
                    cmd = Console.ReadLine();
                }

                context.CloseBurnClient();
                context.Dispose();
            }
            else
            {
                Console.WriteLine(result.message);

                string cmd = "";
                while (cmd != "exit")
                {
                    cmd = Console.ReadLine();
                }

                Run(username, password, logtype);
            }
        }

        private static void RunAsService(string username, string password, string logtype)
        {
            BurnServiceContext context = new BurnServiceContext();
            var result = context.Init(username, password, logtype, true);

            if (result.success)
            {
                context.OpenBurnClient();

                Console.WriteLine("PSDBurnService is Running...");

                string cmd = "";
                while (cmd != "exit")
                {
                    cmd = Console.ReadLine();
                }

                context.CloseBurnClient();
                context.Dispose();
            }
            else
            {
                Console.WriteLine("PSDBurnService Failed：" + result.message);
                Console.ReadLine();
            }
        }
    }
}
